<?php

namespace IDock\Insurance\DAJIA\Response;

use IDock\Http\Request;
use IDock\Http\Response;

class AllDAJIAResponse extends Response
{

    protected $status = '';

    protected $logicStatus = '';

    public function resolve(): Response
    {
        $body = $this->getBody();

        if ($body) {
            $body = json_decode($body,true);
            $errorCode = $body['status'] ?? '';
            $error = $body['error'] ?? '';
            $message = $body['message'] ?? '';

            if ($errorCode) {
                $this->setError( $error ? $error.":".$message : '未知错误');
                return  $this;
            }

            $this->setBody($body);
        }

        return $this;
    }

    public function decrypt($seed,Request $request)
    {
        $body = $this->getBody();
        $data = $body['data'] ?? '';
        if(empty($data)){
            $this->setError( '待解密数据为空');
            return  $this;
        }
        //对应java AES加密的SHA1PRNG算法
        $realKey = substr(openssl_digest(openssl_digest($seed, 'sha1', true), 'sha1', true), 0, 16);
        $res = openssl_decrypt(hex2bin($data),'aes-128-ecb',$realKey,OPENSSL_RAW_DATA);
        if(!$res){
            $this->setError( '解密失败');
            return  $this;
        }
        $request->decryptLogs($request->getRequestId(),$res);
        $resp = json_decode($res,true);
        if($resp['code'] != '2000'){
            $this->setError($resp['message'] ?? '未知错误');
            $this->status = $resp['code'];
            return $this;
        }
        $bodyStatus = $resp['body']['status'] ?? '';
        if(!in_array($bodyStatus,['0000','0001','0002','2000']) && $bodyStatus != ''){
            $this->setError($resp['body']['message'] ?? '');
            $this->logicStatus = $resp['body']['status'] ?? '';
            return $this;
        }
        //大家保个性十足的message提示字段
//        $messageKey = [
//            'orderMessage',
//            'syAppStatusMessage',
//        ];
//        foreach ($messageKey as $key){
//            if(isset($resp['body']['result'][$key])){
//                $this->setError($resp['body']['result'][$key]);
//                break;
//            }
//        }
        $this->setBody($resp);
        return $this;
    }

    /**
     * @return string
     */
    public function getStatus(): string
    {
        return $this->status;
    }

    /**
     * @return string
     */
    public function getLogicStatus(): string
    {
        return $this->logicStatus;
    }


}
